﻿using System;
using System.Collections.Generic;
using System.Data.SQLite;
using PostSharp.Aspects;
using YuYuKiCms.Framework.UnitTest;

namespace DALTest.Aspect
{
    [Serializable]
    public class TruncateDataAttribute : OnMethodBoundaryAspect
    {
        #region Method internal

        #region Overrides of OnMethodBoundaryAspect

        public override void OnEntry(MethodExecutionArgs args)
        {
            TruncateAllData();
            base.OnEntry(args);
        }

        public override void OnExit(MethodExecutionArgs args)
        {
            base.OnExit(args);
            TruncateAllData();
        }

        #endregion

        private void TruncateAllData()
        {
            //"select * from sqlite_sequence"
            var tables = GetTables();
            DeleteAllContent(tables);
        }

        private void DeleteAllContent(IEnumerable<string> tables)
        {
            const string query = "DELETE from {0}";
            SQLiteConnection sqConnection = null;
            try
            {
                sqConnection = new SQLiteConnection(Helper.ConnectionString);
                sqConnection.Open();

                foreach (var table in tables)
                {
                    var sqCommand = new SQLiteCommand(string.Format(query, table), sqConnection);
                    sqCommand.ExecuteNonQuery();
                }
            }
            finally
            {
                // always call Close when done reading. 
                if (sqConnection != null) sqConnection.Close();
            }

        }

        private IEnumerable<string> GetTables()
        {
            const string query = "SELECT name FROM sqlite_master WHERE type='table'";
            var tables = new List<string>();
            SQLiteConnection sqConnection = null;
            SQLiteDataReader sqReader = null;
            try
            {
                sqConnection = new SQLiteConnection(Helper.ConnectionString);
                sqConnection.Open();

                var sqCommand = new SQLiteCommand(query, sqConnection);

                sqReader = sqCommand.ExecuteReader();
                while (sqReader.Read())
                {
                    tables.Add(sqReader.GetString(0));
                }
            }
            finally
            {
                // always call Close when done reading. 
                if (sqReader != null) sqReader.Close();
                // always call Close when done reading. 
                if (sqConnection != null) sqConnection.Close();
            }

            return tables;
        }

        #endregion
    }
}